<template>
  <div :id="id"></div>
</template>

<script>
  import G2 from 'g2'
  var data = [{
    item: '未完成24项',
    count: 40,
    percent: 0.4
  }, {
    item: '完成64项',
    count: 60,
    percent: 0.6
  }]
  export default {
    name: '',
    data () {
      return {
        chart: null
      }
    },
    props: {
      charData: {
        type: Array,
        default: data
      },
      id: String
    },
    mounted: function () {
      this.drawChart(data);       // 第一步想到的是创建的时候更新图表，但是这个不适用于异步请求接口获取相关数据，所以采用下面的监听的方式
    },
    beforeUpdate: function () {
      this.drawChart();
    },
    watch: {
      charData: function (val, oldVal) {    // 监听charData，当放生变化时，触发这个回调函数绘制图表
        console.log('new: %s, old: %s', val, oldVal);
        this.drawChart(val);
      }
    },
    methods: {
      drawChart: function (datas) {
        this.chart && this.chart.destroy();
        let data = datas;
        this.chart = new G2.Chart({
          id: this.id,
          forceFit: true,
          width: 150,
          height: 150
        });
        let chart = this.chart;
        chart.source(data, {
          percent: {
            formatter: function formatter(val) {
              val = val * 100 + '%';
              return val;
            }
          }
        });
        chart.coord('theta');
        chart.tooltip({
          showTitle: false
        });
        chart.intervalStack().position('percent').color('item').label('percent', {
          offset: 0,
          // autoRotate: false,
          textStyle: {
            textAlign: 'center',
            shadowBlur: 2,
            shadowColor: '#fff'
          }
        })
        chart.render();
      }
    }
  }
</script>

<style scoped lang="">

</style>
